package com.wufun.overseas.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JavaType;
import com.wufun.baselibrary.download.CommonDownloadFactory;
import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.impl.AdapterInterface;
import com.wufun.baselibrary.net.HttpUtils;
import com.wufun.overseas.R;
import com.wufun.overseas.adapters.ForumPostsAdapter;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.models.bean.ForumBean;
import com.wufun.overseas.models.bean.ForumData;
import com.wufun.overseas.models.bean.RespBean;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.rpc.RpcConstant;
import com.wufun.overseas.tools.DownloadManager;
import com.wufun.overseas.utils.HtmlDocUtil;
import com.wufun.overseas.utils.JsonMapper;
import com.wufun.overseas.utils.StringUtils;
import com.wufun.overseas.view.ForumLoadingView;
import com.wufun.overseas.view.IXListViewLoadMore;
import com.wufun.overseas.view.IXListViewRefreshListener;
import com.wufun.overseas.view.XListView4NewGame;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 帖子详情
 * papa项目的bar是mg_forum_title_layout
 */
public class PostDetailsActivtiy extends MyActivity implements View.OnClickListener, AdapterInterface {
    private static final String TAG = PostDetailsActivtiy.class.getSimpleName();
    public static final String KEY_FORUM_POSTS_BEAN = TAG + "key_forum_posts_bean";

    @Bind(R.id.actionbarLayout)
    RelativeLayout actionbarLayout;
    @Bind(R.id.back_image)
    ImageView back_image;
    @Bind(R.id.layout_title)
    TextView layout_title;
    @Bind(R.id.mg_forum_post_comment_list)
    XListView4NewGame mg_forum_post_comment_list;
    @Bind(R.id.loadingView)
    ForumLoadingView loadingView;
    @Bind(R.id.postFunction)
    LinearLayout postFunction;
    @Bind(R.id.postFuncHost)
    TextView postFuncHost;
    @Bind(R.id.postFuncMore)
    LinearLayout postFuncMore;

    private int btn_index;
    protected CommonDownloadFactory factory;
    //input control
//    @Bind(R.id.layout_chat_cell_container)
//    LinearLayout  layout_chat_cell_container;

//    @Bind(R.id.btn_chat_praise)
//    Button btn_chat_praise;
//    @Bind(R.id.btn_chat_send)
//    Button        btn_chat_send;
//    @Bind(R.id.edit_comment_count)
//    TextView      edit_comment_count;
//    @Bind(R.id.image_add)
//    ImageView     image_add;
//    @Bind(R.id.footer_tip)
//    TextView      footer_tip;
//    @Bind(R.id.btn_chat_extension)
//    Button        btn_chat_extension;
//    @Bind(R.id.chat_layout_more)
//    LinearLayout  chat_layout_more;
//    @Bind(R.id.chat_layout_extension)
//    View          chat_layout_extension;
//    @Bind(R.id.chat_layout_extension_container)
//    LinearLayout  chat_layout_extension_container;


    ForumPostsAdapter newAdapter;
    List<ForumPostsAdapter.ViewBean> listData;

    ForumPostsAdapter.ViewBean.PostGame item;
    ForumBean.ForumPostsBean forumPostsBean;
    volatile List<ForumBean.ForumCommentBean> forumCommentBeans;
    private int type = 0;  //type 1 正常的帖子详情。 type 2 搜索页面
    private String tid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mg_forum_post_activity);
        ButterKnife.bind(this);
        rootBarRl.setVisibility(View.GONE);
        factory = CommonDownloadFactory.get();
        factory.setListener(this);
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        layout_title.setText(getString(R.string.forum_post_detail));
        layout_title.setText(title);
        type = intent.getIntExtra("type", 0);
        tid = intent.getStringExtra("Tid");

        newAdapter = new ForumPostsAdapter(this, this);
        listData = new ArrayList<ForumPostsAdapter.ViewBean>();

        mg_forum_post_comment_list.setAdapter(newAdapter);


        mg_forum_post_comment_list.setPullLoadEnable(new IXListViewLoadMore() {
            @Override
            public void onLoadMore() {

            }
        });
        mg_forum_post_comment_list.setPullRefreshEnable(new IXListViewRefreshListener() {
            @Override
            public void onRefresh() {
                getDataNet(tid);
            }
        });


        back_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getDataNet(tid);

    }

    public void getDataNet(String pid) {
        HttpUtils.doGet(RpcConstant.forumRootUrl + "/forum/detail?pid=" + pid + "&limit=10&see_lz=0&comment_order=asc&uid=30236975&token=vVv4U6REug8dyI5Z", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mg_forum_post_comment_list.setNoMore();
                        showToast(getResources().getString(R.string.getnetdata_error));
                    }
                });

                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String s = response.body().string();
                    if (s != null) {
                        JavaType javaType = JsonMapper.getInstance().createCollectionType(RespBean.class, ForumData.ForumPostsData.class);
                        RespBean<ForumData.ForumPostsData> respBean = JsonMapper.getInstance().fromJson(s, javaType);

                        //下拉获取更多  追加
                        if (respBean != null && respBean.getData() != null) {
                            forumPostsBean = respBean.getData().getPosts();
                            forumCommentBeans = respBean.getData().getComment_list();
                            notifyDataSetChanged();
                        }

                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mg_forum_post_comment_list.stopRefresh();
                                mg_forum_post_comment_list.stopLoadMore();
                                mg_forum_post_comment_list.setNoMore();
                            }
                        });
                    }
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mg_forum_post_comment_list.stopRefresh();
                            mg_forum_post_comment_list.stopLoadMore();
                            mg_forum_post_comment_list.setNoMore();
                        }
                    });
                    e.printStackTrace();
                }


            }
        });
    }


    void notifyDataSetChanged() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (forumPostsBean == null)
                    return;
                listData.clear();
                try {

                    setPostViewData(forumPostsBean, true);
//            if (adView != null)
//                listData.add(new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.BAIDUADBANNER, adView));

                    for (int i = 0; forumCommentBeans != null && i < forumCommentBeans.size(); i++) {
                        ForumBean.ForumCommentBean commentBean = forumCommentBeans.get(i);
                        setCommentViewData(commentBean, i == 0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                notifyAdapter();
            }
        });
    }

    void notifyAdapter() {
        loadingView.change(ForumLoadingView.LOADING_SUCCESS);
        newAdapter.setItemBeans(listData);
        Log.e("TAG", listData.toString());
        newAdapter.notifyDataSetChanged();
        mg_forum_post_comment_list.stopRefresh();
        mg_forum_post_comment_list.stopLoadMore();
        mg_forum_post_comment_list.setNoMore();
    }

    synchronized void setPostViewData(ForumBean.ForumPostsBean posts, boolean isShowFooterDivider) {
        if (listData == null) {
            listData = new ArrayList<ForumPostsAdapter.ViewBean>();
        }
//        listData.clear();

        //header
        ForumPostsAdapter.ViewBean headerBean = new ForumPostsAdapter.ViewBean(
                ForumPostsAdapter.ViewType.POST_HEADER1,
                new ForumPostsAdapter.ViewBean.PostHeader1(
                        true,
                        posts.getUid(),
                        posts.getAvatar_src(),
                        posts.getNickname(),
                        posts.getAdd_time(),
                        posts.getFirst() > 0,
                        posts.getPid(),
                        posts.getForum_auth() == 1,
                        posts.isOfficialAccount(),
                        posts.getSolve_flg(),
                        posts.getVip_level(),
                        posts.getSvip_level(),
                        posts.getCopper_title() != null ? posts.getCopper_title().getBattleTitle() : "",
                        posts.getCopper_title() != null ? posts.getCopper_title().getBattleColor() : "",
                        posts.is_moderator(),
                        posts.getMember_honor(),
                        posts.getFname(),
                        posts.getFid()
                ));
        listData.add(headerBean);

        //subject
        if ((posts.getSubject() != null && !StringUtils.isEmpty(posts.getSubject().trim()))
                || (posts.getTag_list() != null && posts.getTag_list().size() != 0)) {
            ForumPostsAdapter.ViewBean subjectBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.POST_SUBJECT, new ForumPostsAdapter.ViewBean.PostSubject(
                    posts.getBest() > 0,
                    posts.getSubject(),
                    posts.getHelp() > 0,
                    posts.getHelp_money() + "",
                    posts.getTag_info(),
                    posts.getTag_list(),
                    posts.getFid(),
                    posts.getFname()
            ));
            listData.add(subjectBean);
        }

        try {
            String actionBarTitle = "";
            if (StringUtils.isNotEmpty(posts.getSubject())) {
                actionBarTitle = posts.getSubject();
            } else if (StringUtils.isNotEmpty(posts.getMessage())) {
                actionBarTitle = posts.getMessage();
            }
            if (!StringUtils.isEmpty(posts.getMessage())) {

                //message -- new
                List<String> postLargeImageList = new ArrayList<String>();
                if (!StringUtils.isEmpty(posts.getMessage().trim()) && HtmlDocUtil.isPostDoc(posts.getMessage())) {
                    boolean showBest = StringUtils.isEmpty(posts.getSubject().trim()) && posts.getBest() > 0;
                    boolean showAsk = StringUtils.isEmpty(posts.getSubject().trim()) && posts.getHelp() > 0;
                    boolean showTag = (posts.getSubject() == null || StringUtils.isEmpty(posts.getSubject().trim())
                            && (posts.getTag_list() == null || posts.getTag_list().size() == 0));
                    List<HtmlDocUtil.PostDetail> details = HtmlDocUtil.getPostDetail(posts.getMessage());
                    for (int i = 0; i < details.size(); i++) {
                        HtmlDocUtil.PostDetail detail = details.get(i);
                        ForumPostsAdapter.ViewBean messageBean = null;
                        switch (detail.type) {
                            case Text:
                                Log.e("TAGpost", "txt");
                                messageBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.POST_MESSAGE, new ForumPostsAdapter.ViewBean.PostMessage(
                                        showBest == true && i == 0,
                                        ((HtmlDocUtil.PostText) detail.getContent()).getText(),
                                        showAsk == true && i == 0,
                                        posts.getHelp_money() + "",
                                        showTag == true && i == 0 ? posts.getTag_info() : null
                                ));
                                break;
                            case Image:
                                HtmlDocUtil.PostImage postImage = (HtmlDocUtil.PostImage) detail.getContent();
                                postLargeImageList.add(getCdnUrl(posts.getCdn_url(), postImage.getImgUrlLarge()));
                                messageBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.POST_IMAGE, new ForumPostsAdapter.ViewBean.PostImage(
                                        getCdnUrl(posts.getCdn_url(), postImage.getImgUrl()),
                                        postLargeImageList.size() - 1,
                                        postLargeImageList
                                ));
                                break;
                            case Video:
                                HtmlDocUtil.PostVideo postVideo = (HtmlDocUtil.PostVideo) detail.getContent();
                                messageBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.POST_VIDEO, new ForumPostsAdapter.ViewBean.PostVideo(
                                        getCdnUrl(posts.getCdn_url(), postVideo.getImgUrl()),
                                        postVideo.videoUrl,
                                        actionBarTitle
                                ));
                                break;
                        }
                        listData.add(messageBean);
                    }
                } else {
                    ForumPostsAdapter.ViewBean messageBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.POST_MESSAGE, new ForumPostsAdapter.ViewBean.PostMessage(
                            StringUtils.isEmpty(posts.getSubject().trim()) && posts.getBest() > 0,
                            new SpannableStringBuilder().append(posts.getMessage()),
                            (posts.getSubject() != null || StringUtils.isEmpty(posts.getSubject().trim())) ? posts.getTag_info() : null
                    ));
                    listData.add(messageBean);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        //reference game info
        if (posts.getRelation_game() != null
                && !TextUtils.isEmpty(posts.getRelation_game().getGame_id())) {
            ForumPostsAdapter.ViewBean gameBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.POST_GAME, new ForumPostsAdapter.ViewBean.PostGame(
                    posts.getPid() + "",
                    posts.getRelation_game()
            ));
            listData.add(gameBean);
        }


        //reference EMPLOYEE_TAGS
        if (posts.getEmploy_tags() != null && posts.getEmploy_tags().size() != 0) {
            ForumPostsAdapter.ViewBean gameBean = new ForumPostsAdapter.ViewBean(
                    ForumPostsAdapter.ViewType.EMPLOYEE_TAGS,
                    new ForumPostsAdapter.ViewBean.EmployeeTags(
                            posts.getEmploy_tags(),
                            posts.getFid(),
                            posts.getFname()
                    ));
            listData.add(gameBean);
        }


        //footer1
        ForumPostsAdapter.ViewBean footerBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.POST_FOOTER1, new ForumPostsAdapter.ViewBean.PostFooter(
                posts.getPid(),
                posts.getFid(),
                posts.getFname(),
                posts.getView(),
                posts.getCommit(),
                posts.getPraise(),
                posts.is_praise(),
                isShowFooterDivider
        ));
        listData.add(footerBean);

    }


    List<String> getCdnUrls(String cdnUrl, List<String> imgUrls) {
        if (imgUrls == null || imgUrls.size() == 0) return null;
        List<String> ret = new ArrayList<String>();
        for (int i = 0; i < imgUrls.size(); i++) {
            String url = imgUrls.get(i);
            ret.add(getCdnUrl(cdnUrl, url));
        }

        return ret;
    }


    String getCdnUrl(String cdnUrl, String imgUrl) {
        if (StringUtils.isEmpty(imgUrl)) return null;
        String ret = "";
        if (imgUrl.startsWith(cdnUrl)) return imgUrl;
        else {
            ret = cdnUrl + imgUrl;
        }

        return ret;
    }

    synchronized void setCommentViewData(ForumBean.ForumCommentBean commentBean, boolean showDivider) {
        if (listData == null) {
            listData = new ArrayList<ForumPostsAdapter.ViewBean>();
        }
        if (commentBean == null || forumPostsBean == null) return;

        //header
//        AccountBean accountBean     = AccountUtil_.getInstance_(this).getAccountData();
        boolean isModerator = (commentBean.getForum_auth() == 1);
        boolean officialAccount = commentBean.isOfficialAccount();
        boolean isHelp = (forumPostsBean.getHelp() == 1);
        boolean iSolve = (forumPostsBean.getSolve_flg() == 1);
        int myAuth = forumPostsBean.getAuth();
//        boolean     isMyPost        = (accountBean != null && accountBean.getUid() == forumPostsBean.getUid());
//        boolean     isMyComment     = (accountBean != null && commentBean.getUid() == accountBean.getUid());
        boolean isMyPost = false;
        boolean isMyComment = false;
        boolean isHostComment = (commentBean.getUid() == forumPostsBean.getUid());
        ForumPostsAdapter.ViewBean headerBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.COMMENT_HEADER, new ForumPostsAdapter.ViewBean.CommentHeader(
                showDivider,
                commentBean.getUid(),
                commentBean.getPid(),
                commentBean.getAvatar_src(),
                commentBean.getNickname(),
                commentBean.getAdd_time(),
                isHostComment,//评论是否为版主
                commentBean.getFloor(),
                isModerator,//评论者是否为版主
                officialAccount,//评论者是否为官方
                commentBean.getAnswer_flg(),
                isHelp && (!iSolve && (isMyPost && (!isMyComment))),//1.必须是求助帖，2.如果已采纳则不再显示，3.只有楼主有采纳功能，4.自己的评论不能采纳
                !isMyComment,//自己的评论/回复没有举报，但是别人的评论可以举报,
                myAuth == 3 || myAuth == 99 || isMyComment || isMyPost,//可以删除评论的条件：评论属于我（isMyComment）,专区版主(3),超级用户(99),我的帖子（isMyPost）
                commentBean.getVip_level(),
                commentBean.getSvip_level(),
                commentBean.is_moderator(),
                commentBean.getMember_honor()
        ));
        listData.add(headerBean);

        //message
        ForumPostsAdapter.ViewBean messageBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.COMMENT_MESSAGE, new ForumPostsAdapter.ViewBean.CommentMessage(
                commentBean.getPid(),
                commentBean.getMessage(),
                commentBean.getNickname(),
                commentBean.getUid(),
                !isMyComment,//自己的评论/回复没有举报，但是别人的评论可以举报,
                myAuth == 3 || myAuth == 99 || isMyComment//可以删除评论的条件：评论属于我（isMyComment），专区版主(3),超级用户(99)
        ));
        listData.add(messageBean);

        //messageImage
        for (int i = 0; commentBean.getPic_list() != null && i < commentBean.getPic_list().size(); i++) {
            ForumPostsAdapter.ViewBean messageImageBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.COMMENT_IMAGE, new ForumPostsAdapter.ViewBean.CommentImage(
                    commentBean.getPic_list().get(i),
                    i,
                    commentBean.getRaw_pic_list()
            ));
            listData.add(messageImageBean);
        }

        //reply
        ForumPostsAdapter.ViewBean footerBean = new ForumPostsAdapter.ViewBean(ForumPostsAdapter.ViewType.COMMENT_MESSAGE_REPLY, new ForumPostsAdapter.ViewBean.CommentMessageReply(
                commentBean.getPid(),
                commentBean,
                myAuth,
                commentBean.getReply_list() != null && commentBean.getReply_list().size() > 0,
                isMyPost
        ));
        listData.add(footerBean);
    }


    @Override
    public void onClick(View v) {

    }


    @Override
    public void onAdapterItemClick(View view, int position) {
        btn_index = position;
        DownLoadModel start = null;
        try {
            item = (ForumPostsAdapter.ViewBean.PostGame) listData.get(btn_index).getObj();
            if (item != null && item.gameInfo != null) {
                if (item.gameInfo.getGame_down_url_mote() == null || item.gameInfo.getGame_down_url_mote().indexOf("apk") != -1) {
                    Toast.makeText(PostDetailsActivtiy.this, "URI ERROR", Toast.LENGTH_SHORT).show();
                    return;
                }
                start = DownloadManager.getInstance().getDownloadByUrl(item.gameInfo.getGame_down_url_mote());

                if (start != null) {
                    if (start.getStatus() == CommonDownloadTask.STATUS_FINISH) {
                        StartGame(item.gameInfo.getGame_down_url_mote(), start.getGamePath() + "/" + start.getGameZipName().replace(".zip", ""));
                    } else if (start.getStatus() == CommonDownloadTask.STATUS_STOP) {
                        download(start);
                    } else if (start.getStatus() == CommonDownloadTask.STATUS_PROGRESS) {
                        if (factory.isExitTask(start.getDownloadUrl()))
                            factory.cancelTask(start.getDownloadUrl());
                        else {
                            download(start);
                        }
                    } else {
                        download(start);
                    }
                } else {
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < item.gameInfo.getGame_tag_info().size(); i++) {
                        if (i < (item.gameInfo.getGame_tag_info().size() - 1)) {
                            sb.append(item.gameInfo.getGame_tag_info().get(i).getId() + ",");
                        } else {
                            sb.append(item.gameInfo.getGame_tag_info().get(i).getId());
                        }
                    }
                    addDownloadToDB(item.gameInfo.getGame_name(),
                            item.gameInfo.getGame_down_url_mote(),
                            item.gameInfo.getGame_id(),
                            item.gameInfo.getGame_ico_remote(),
                            item.gameInfo.getGame_size(),
                            sb.toString());
                    Intent intent = new Intent(PostDetailsActivtiy.this, DownloadManagerActivity.class);
                    intent.putExtra("title", "Download Management");
                    startActivity(intent);
                }
            } else {
                Toast.makeText(PostDetailsActivtiy.this, "URI ERROR", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(PostDetailsActivtiy.this, "URI ERROR", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }

    private void download(DownLoadModel start) {
        try {
            factory.addTask(new CommonDownloadTask(start.getDownloadUrl()
                    , start.getGameZipName()
                    , start.getDownloadDir()
                    , start.getGameName()));
        } catch (Exception e) {
            showToast(e.getMessage());
        }
    }

    @Override
    public void onDownloadProgress(String url, int progress, String speed) {
        super.onDownloadProgress(url, progress, speed);
        newAdapter.getSpeed(progress, speed);
        newAdapter.setReflash();
    }

    @Override
    public void onDownloadStart(String url, String gameName) {
        newAdapter.setReflash();
    }


    @Override
    public void onDownloadFinish(String url, String gameName) {
        newAdapter.setReflash();
    }

    @Override
    public void onDownloadError(String url, String gameName) {
        newAdapter.setReflash();
    }

    @Override
    public void onDownloadStop(String url, String gameName) {
        newAdapter.setReflash();
    }

    @Override
    public void onDownloadZIPError(String url, String gameName) {
        super.onDownloadZIPError(url, gameName);
        newAdapter.setReflash();
    }

    @Override
    public void onDownloadStarZIP(String url, String gameName) {
        super.onDownloadStarZIP(url, gameName);
        newAdapter.setReflash();
    }

    @Override
    public void onDownloadZIPProgress(String url, int progress, String speed) {
        super.onDownloadZIPProgress(url, progress, speed);
        newAdapter.setReflash();
    }
}
